package com.mj.haier.calc.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.mj.haier.calc.client.RrskxClient;
import com.mj.haier.calc.domain.AzEorderTitle;
import com.mj.haier.calc.repository.AzEorderTitleRepository;
import com.mj.haier.calc.repository.search.AzEorderTitleSearchRepository;
import com.mj.haier.calc.web.rest.errors.BadRequestAlertException;
import com.mj.haier.calc.web.rest.util.HeaderUtil;
import com.mj.haier.calc.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing AzEorderTitle.
 */
@RestController
@RequestMapping("/api")
public class AzEorderTitleResource {

    private final Logger log = LoggerFactory.getLogger(AzEorderTitleResource.class);

    private static final String ENTITY_NAME = "microCalcAzEorderTitle";

    private final AzEorderTitleRepository azEorderTitleRepository;

    private final AzEorderTitleSearchRepository azEorderTitleSearchRepository;

    private final RrskxClient rrskxClient;

    public AzEorderTitleResource(AzEorderTitleRepository azEorderTitleRepository, AzEorderTitleSearchRepository azEorderTitleSearchRepository, RrskxClient rrskxClient) {
        this.azEorderTitleRepository = azEorderTitleRepository;
        this.azEorderTitleSearchRepository = azEorderTitleSearchRepository;
        this.rrskxClient = rrskxClient;
    }

    /**
     * POST  /az-eorder-titles : Create a new azEorderTitle.
     *
     * @param azEorderTitle the azEorderTitle to create
     * @return the ResponseEntity with status 201 (Created) and with body the new azEorderTitle, or with status 400 (Bad Request) if the azEorderTitle has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/az-eorder-titles")
    @Timed
    public ResponseEntity<AzEorderTitle> createAzEorderTitle(@Valid @RequestBody AzEorderTitle azEorderTitle) throws URISyntaxException {
        log.debug("REST request to save AzEorderTitle : {}", azEorderTitle);
        // 主键通过接口参数传入
        // if (azEorderTitle.getOrderCode() != null) {
        //     throw new BadRequestAlertException("A new azEorderTitle cannot already have an orderCode", ENTITY_NAME, "orderCodeexists");
        // }
        log.debug("调用远程服务： {}", rrskxClient.getBdSwitcher(azEorderTitle.getTradeCode()).toString());
        AzEorderTitle result = azEorderTitleRepository.save(azEorderTitle);
        azEorderTitleSearchRepository.save(result);
        return ResponseEntity.created(new URI("/api/az-eorder-titles/" + result.getOrderCode()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getOrderCode().toString()))
            .body(result);
    }

    /**
     * PUT  /az-eorder-titles : Updates an existing azEorderTitle.
     *
     * @param azEorderTitle the azEorderTitle to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated azEorderTitle,
     * or with status 400 (Bad Request) if the azEorderTitle is not valid,
     * or with status 500 (Internal Server Error) if the azEorderTitle couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/az-eorder-titles")
    @Timed
    public ResponseEntity<AzEorderTitle> updateAzEorderTitle(@Valid @RequestBody AzEorderTitle azEorderTitle) throws URISyntaxException {
        log.debug("REST request to update AzEorderTitle : {}", azEorderTitle);
        if (azEorderTitle.getOrderCode() == null) {
            throw new BadRequestAlertException("Invalid orderCode", ENTITY_NAME, "orderCodenull");
        }
        log.debug("调用远程服务： {}", rrskxClient.getBdSwitcher(azEorderTitle.getTradeCode()).toString());
        AzEorderTitle result = azEorderTitleRepository.save(azEorderTitle);
        azEorderTitleSearchRepository.save(result);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, azEorderTitle.getOrderCode().toString()))
            .body(result);
    }

    /**
     * GET  /az-eorder-titles : get all the azEorderTitles.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of azEorderTitles in body
     */
    @GetMapping("/az-eorder-titles")
    @Timed
    public ResponseEntity<List<AzEorderTitle>> getAllAzEorderTitles(Pageable pageable) {
        log.debug("REST request to get a page of AzEorderTitles");
        Page<AzEorderTitle> page = azEorderTitleRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/az-eorder-titles");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * GET  /az-eorder-titles/:id : get the "id" azEorderTitle.
     *
     * @param id the id of the azEorderTitle to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the azEorderTitle, or with status 404 (Not Found)
     */
    @GetMapping("/az-eorder-titles/{orderCode}")
    @Timed
    public ResponseEntity<AzEorderTitle> getAzEorderTitle(@PathVariable String orderCode) {
        log.debug("REST request to get AzEorderTitle : {}", orderCode);
        Optional<AzEorderTitle> azEorderTitle = azEorderTitleRepository.findByOrderCode(orderCode);
        return ResponseUtil.wrapOrNotFound(azEorderTitle);
    }

    /**
     * DELETE  /az-eorder-titles/:id : delete the "id" azEorderTitle.
     *
     * @param id the id of the azEorderTitle to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/az-eorder-titles/{orderCode}")
    @Timed
    public ResponseEntity<Void> deleteAzEorderTitle(@PathVariable String orderCode) {
        log.debug("REST request to delete AzEorderTitle : {}", orderCode);

        azEorderTitleRepository.deleteByOrderCode(orderCode);
        azEorderTitleSearchRepository.deleteByOrderCode(orderCode);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, orderCode.toString())).build();
    }

    /**
     * SEARCH  /_search/az-eorder-titles?query=:query : search for the azEorderTitle corresponding
     * to the query.
     *
     * @param query the query of the azEorderTitle search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/az-eorder-titles")
    @Timed
    public ResponseEntity<List<AzEorderTitle>> searchAzEorderTitles(@RequestParam String query, Pageable pageable) {
        log.debug("REST request to search for a page of AzEorderTitles for query {}", query);
        Page<AzEorderTitle> page = azEorderTitleSearchRepository.search(queryStringQuery(query), pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/az-eorder-titles");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

}
